class PasswordRules extends HTMLElement {
  connectedCallback() {
    this.input = document.getElementById(this.dataset.inputId);
    if (!this.input) return;
    this.rules = [];
    this.setupRules();
    this.input.addEventListener("input", this);
  }
  handleEvent(e) {
    this.score = 0;
    for (let [index, rule] of this.rules.entries()) {
      const match = e.target.value.match(rule);
      if (match) this.score++;
      this.toggleMatchedRuleClass(index, match);
    }
    this.setAttributes("score", this.score);
  }
  setAttributes(name, value) {
    this.dataset[name] = value;
    this.style.setProperty(`--${name}`, value);
  }
  setupRules() {
    const rules = this.dataset.rules;
    if (!rules) return;
    rules.split(this.dataset.separator || ",").forEach((match) => {
      this.rules.push(new RegExp(match.trim()));
    });
    this.setAttributes("total", this.rules.length);
  }

  toggleMatchedRuleClass(index, value) {
    const el = this.querySelector(`[data-rule-index="${index}"]`);
    if (!el) return;
    el.classList.toggle("is-match", value);
  }
}

class PasswordToggle extends HTMLElement {
  // 当组件被连接到DOM时调用
  connectedCallback() {
    // 获取input元素
    this.input = document.getElementById(this.dataset.inputId);
    // 获取status元素
    this.status = document.getElementById(this.dataset.statusId);
    // 获取button元素
    this.btn = this.querySelector("button");
    // 如果input或button元素不存在，则返回
    if (!this.input || !this.btn) return;
    // 设置button元素的ariaPressed属性为false
    this.btn.ariaPressed = false;
    // 设置button元素的ariaLabel属性为"Show password"
    this.btn.ariaLabel = "Show password";
    // 设置button元素的aria-controls属性为input元素的id
    this.btn.setAttribute("aria-controls", this.dataset.inputId);
    // 给button元素添加点击事件监听器，监听者为this
    this.btn.addEventListener("click", this);
  }

  // 处理事件
  handleEvent(e) {
    // 如果输入框的类型是密码
    if (this.input.type === "password") {
      // 设置按钮的ariaPressed属性为true
      this.btn.ariaPressed = true;
      // 设置按钮的ariaLabel属性为"Hide password"
      this.btn.ariaLabel = "Hide password";
      // 将输入框的类型设置为文本
      this.input.type = "text";

      // 如果状态存在
      if (this.status) {
        // 设置状态文本为"Password is visible"
        this.status.textContent = "Password is visible";
      }
    } else {
      // 设置按钮的ariaPressed属性为false
      this.btn.ariaPressed = false;
      // 设置按钮的ariaLabel属性为"Show password"
      this.btn.ariaLabel = "Show password";
      // 将输入框的类型设置为密码
      this.input.type = "password";
      // 如果状态存在
      if (this.status) {
        // 设置状态文本为"Password is hidden"
        this.status.textContent = "Password is hidden";
      }
    }
  }
}

customElements.define("password-rules", PasswordRules);
customElements.define("password-toggle", PasswordToggle);
